package com.fighYo.trace.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fighYo.trace.entity.Payment;
import com.fighYo.trace.entity.Qrcode;
import com.fighYo.trace.entity.User;
import com.fighYo.trace.mapper.QrcodeMapper;
import com.fighYo.trace.service.QrcodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fighYo.trace.service.UserService;
import com.fighYo.trace.utils.QRUtil;
//import com.fighYo.trace.utils.QRUtils;
import com.fighYo.trace.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fighYo
 * @since 2022-04-15
 */
@Slf4j
@Service
public class QrcodeServiceImpl extends ServiceImpl<QrcodeMapper, Qrcode> implements QrcodeService {

    @Autowired
    private UserService userService;

    @Autowired
    private QrcodeService qrcodeService;

    @Autowired
    private QRUtil qrUtil;

    @Override
    public Qrcode getQrcodeByUUID(String uuid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uuid", uuid);
        Qrcode qrcode = baseMapper.selectOne(wrapper);
        return qrcode;
    }

    @Override
    public void createQR(Payment payment) throws Exception {
        try {
            String userId = payment.getBuyerId();
            User user = userService.getById(userId);
            if (!user.getUserType().equals("2")) {
                log.info("用户身份不支持生成溯源码");
                return;
            }

            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 11);

            while (getQrcodeByUUID(uuid) != null) {
                uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 11);
            }

            String url = qrUtil.createQR(uuid);
            Qrcode qrcode = new Qrcode();
            qrcode.setUuid(uuid);
            qrcode.setProductName(payment.getProductName());
            qrcode.setPaymentId(String.valueOf(payment.getId()));
            qrcode.setUserId(userId);
            qrcode.setImg(url);
            qrcode.setJudgeFlag("0");

            qrcodeService.save(qrcode);

            log.info("成功生成溯源码: {}", url);
        } catch (Exception ex) {
            log.info("生成溯源码失败: {}", ex.getMessage());
            throw ex;
        }
    }

}
